<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>09_component | KnockOut.js</title>
  <script src="../assets/knockout-3.5.1.js"></script>
</head>
<body>

  <ul data-bind="foreach: products">
    <li class="product">
      <strong data-bind="text: name"></strong>
      <like-widget params="value: userRating"></like-widget>
    </li>
  </ul>
      
  <script type="text/javascript">
    ko.components.register('like-widget', {
      viewModel: function(params) {
        // 数据：null, 'like', 'dislike'
        this.chosenValue = params.value;
        
        // 行为
        this.like = function() { this.chosenValue('like'); }.bind(this);
        this.dislike = function() { this.chosenValue('dislike'); }.bind(this);
      },
      template:
        '<div class="like-or-dislike" data-bind="visible: !chosenValue()">\
          <button data-bind="click: like">喜欢</button>\
          <button data-bind="click: dislike">不喜欢</button>\
        </div>\
        <div class="result" data-bind="visible: chosenValue">\
          You <strong data-bind="text: chosenValue"></strong> it\
        </div>'
    });

    function Product(name, rating) {
      this.name = name;
      this.userRating = ko.observable(rating || null);
    }

    function MyViewModel() {
      this.products = [
        new Product('西红柿鸡蛋'),
        new Product('小鸡炖蘑菇'),
        new Product('糖醋里脊', 'like') // 'liked'
      ];
    }
        
    ko.applyBindings(new MyViewModel());
  </script>
    
</body>
</html>